package com.api.workflow.web;

import cn.hutool.core.date.DateUtil;
import com.api.workflow.util.YNHttpUtils;
import com.weaver.general.BaseBean;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

/*
 * 接口11   OA获取SAP供应商应付账款
 * */
public class YNFII010Task extends BaseCronJob {
    @Override
    public void execute() {
        BaseBean baseBean = new BaseBean();

        try {


            Date date = DateUtil.date();
            String format = DateUtil.format(date, "yyyyMMdd");
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("CPUDT", format);
            baseBean.writeLog("wyq==FII010==========jsonObject" + jsonObject.toString());
            String post = YNHttpUtils.FII010(jsonObject.toString(), YNHttpUtils.token());
            baseBean.writeLog("wyq==FII010==========post" + post);


            JSONObject jsonPOST = JSONObject.parseObject(post);
            String STATUS = jsonPOST.getString("STATUS");
            String MESSAGE = jsonPOST.getString("MESSAGE");

            if ("S".equals(STATUS)) {
                RecordSet rs1 = new RecordSet();
                JSONArray data = jsonPOST.getJSONArray("DATA");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    //查询数据库是否已存在
                    String select = "select * from uf_yfzkbd where gsdm = '" + jsonObject1.getString("BUKRS") + "' and"
                            + " hjnd = '" + jsonObject1.getString("GJAHR") + "' and"
                            + " hjpzdpzbh = '" + jsonObject1.getString("BELNR") + "' and"
                            + " hjpzzdxxmbh = '" + jsonObject1.getString("BUZEI") + "'";

                    baseBean.writeLog("wyq==FII010==========select" + select);

                    boolean b1 = rs1.execute(select);
                    baseBean.writeLog("wyq==FII010==========b1" + b1);

                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("gsdm", jsonObject1.getString("BUKRS"));
                    objectObjectHashMap.put("gyskmbm", jsonObject1.getString("LIFNR"));
                    objectObjectHashMap.put("fpbh", jsonObject1.getString("ZUONR"));
                    objectObjectHashMap.put("hjnd", jsonObject1.getString("GJAHR"));
                    objectObjectHashMap.put("hjpzdpzbh", jsonObject1.getString("BELNR"));
                    objectObjectHashMap.put("hjpzzdxxmbh", jsonObject1.getString("BUZEI"));
                    objectObjectHashMap.put("bz", jsonObject1.getString("WAERS"));
                    objectObjectHashMap.put("fktjbm", jsonObject1.getString("ZTERM"));
                    objectObjectHashMap.put("zftjdms", jsonObject1.getString("ZTERMMS"));
                    objectObjectHashMap.put("pzhbje", jsonObject1.getString("WRBTR"));
                    objectObjectHashMap.put("lrzx", jsonObject1.getString("PRCTR"));
                    objectObjectHashMap.put("zzhth", jsonObject1.getString("ZZ005"));
                    objectObjectHashMap.put("cgy", jsonObject1.getString("UNSEZ"));
                    String wybs = jsonObject1.getString("BUKRS") + jsonObject1.getString("GJAHR") + jsonObject1.getString("BELNR") + jsonObject1.getString("BUZEI");
                    objectObjectHashMap.put("wybs", wybs);//唯一标识
                    rs1.next();
                    int counts = rs1.getCounts();
                    if (counts == 0) {
                        //插入数据库
                        int modeId = getModeId("uf_yfzkbd");
                        boolean b2 = insetModeData("uf_yfzkbd", objectObjectHashMap, 1, modeId);
                        baseBean.writeLog("wyq==FII010=========插入" + b2);
                    } else {
                        //更新数据库
                        Map<String, Object> whereMap = new HashMap<>();
                        whereMap.put("gsdm", objectObjectHashMap.get("gsdm"));
                        whereMap.put("hjnd", objectObjectHashMap.get("hjnd"));
                        whereMap.put("hjpzdpzbh", objectObjectHashMap.get("hjpzdpzbh"));
                        whereMap.put("hjpzzdxxmbh", objectObjectHashMap.get("hjpzzdxxmbh"));
                        boolean b2 = updateModeData("uf_yfzkbd", objectObjectHashMap, whereMap);
                        baseBean.writeLog("wyq==FII010=========更新" + b2);

                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("wyq==FII010==========Exception" + e.toString());
        }
    }


    /**
     * 插入到建模表数据
     *
     * @param tableName
     * @param data
     * @param hrmResourceId
     * @param modeId
     * @return
     */
    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            columns += (key + ",");
            values += ("?,");
            dataList.add(value);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }

    /**
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }

    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }


}